<?php

declare (strict_types=1);
/**
 * @copyright 深圳市易果网络科技有限公司
 * @version 1.0.0
 * @link https://dayiguo.com
 */

namespace App\Service\User;


use App\Dao\PlatformDao;
use App\Dao\PlatformOrderDao;
use App\Dao\UserDao;
use App\Exception\CustomException;
use App\Kernel\Util\UserJwtInstance;
use App\Service\Service;


use Hyperf\DbConnection\Db;
use Hyperf\Snowflake\IdGeneratorInterface;
use Hyperf\Di\Annotation\Inject;

/**
 * 平台订单服务
 *
 * @author 张昊(2396675557@qq.com)
 * @package App\Service\User
 */
class PlatformOrderService  extends Service
{

    /**
     * 平台订单 DAO
     *
     * @Inject()
     * @var PlatformOrderDao
     */
    private $platform_order_dao;

    /**
     * 平台商品Dao
     * @Inject
     * @var PlatformDao
     */
    private $platform_dao;

    /**
     * @Inject
     *
     * @var PingPpService
     */
    private $ping_service;

    /**
     * @Inject
     * @var UserDao
     */
    private $user_dao;
    /**
     * 平台订单服务
     * @param int $id
     * @param string $channel
     * @return mixed
     */
    public function buy(int $id, string $channel)
    {
        $platform = $this->platform_dao->first(['id' => $id]);

        $order_no = (string)$this->container->get(IdGeneratorInterface::class)->generate();

        $data = [
            'status' => $this->platform_order_dao::STATUS_UNPAID,
            'user_id' => uid(),
            'order_no' => $order_no,
            'product_id' => $id,
            'amount' => $platform['price'],
            'pay_type' => $channel,
            'created_at' => time(),
            'updated_at' => time()
        ];


        $this->platform_order_dao->create($data);

        $result = [
            'amount' => $platform['price'],
            'order_no' => $order_no
        ];

        $payment = $this->ping_service->channel_pay($result, $channel,  $platform['name'], '渠道商购买');

        return $payment;
    }


    /**
     * ping++ 渠道商回调
     *
     * @param array $params
     */
    public function pingNotify($params)
    {
        $where['status'] = $this->platform_order_dao::STATUS_UNPAID;
        $where['order_no'] = substr($params['order_no'],7);
        $platform = $this->platform_order_dao->first($where);
        $platform->trade_id = $params['transaction_no'];
        $platform->status = $this->platform_order_dao::STATUS_PAID;
        $platform->updated_at = time();
        if($platform->save()) {
            $user = $this->user_dao->first($platform['user_id']);
            $user->group_id = 2;
            $user->save();
        }
    }

}